% Feature Selection By Forward Selection
clc;
clearvars;
rng('default');
DataFileName=['Data\UFS_CorrMatrix.mat'];
[Train]=GetDataset(true);

% % % % ReplaceChaseFlag=true;
% % % % if exist(DataFileName,'file')
% % % %     Yes_NO = questdlg({'Cash File Exist','Replace it?'});
% % % %     if strcmp(Yes_NO,'No') || strcmp(Yes_NO,'Cancel')
% % % %         ReplaceChaseFlag=false;
% % % %     end
% % % % end
% % % % if ReplaceChaseFlag
Features=1:29;
% Features=30:39;
X=Train.Features(:,Features);
Names0=Train.FeaturesName(Features);
FNum=size(X,2);
CoefMat0=zeros(FNum);
for i=1:FNum
    for j=i:FNum
        R=corrcoef(X(:,i),X(:,j));
        CoefMat0(i,j)=R(2);
        CoefMat0(j,i)=R(3);
    end
    CoefMat0(i,i)=R(1);
end
% Orders=[1,3,7,10,2,4]
Orders=zeros(1,FNum);
Orders(1)=1;
G=CoefMat0(1,2:end);
I=2:FNum;
Th=0.6;
for i=2:FNum
    [MaxValue,MaxLoc]=max(abs(G));
    if MaxValue>Th
        Orders(i)=I(MaxLoc);
        
    else
        Orders(i)=I(1);
        
    end
    GHat=CoefMat0(Orders(i),:);
    IHat=1:FNum;
    G=[G,GHat];
    I=[I,IHat];

    for o=1:i
        G(I==Orders(o))=[];
        I(I==Orders(o))=[];
    end
end

CoefMat=zeros(FNum);
for i=1:FNum
    for j=i:FNum
        CoefMat(i,j)=CoefMat0(Orders(i),Orders(j));
        CoefMat(j,i)=CoefMat0(Orders(j),Orders(i));
    end
    CoefMat(i,i)=CoefMat0(i,i);
end
Names=Names0(Orders);
% % % % save(DataFileName)
% % % % else
% % % % load(DataFileName)
% % % % end
%%
Table=array2table(CoefMat);
Table.Properties.RowNames=Names;
Table.Properties.VariableNames=Names;
% writetable(Table,'Data\CorCoeff_All.xls')
writetable(Table,'Data\CorCoeff_G1.xls')
% writetable(Table,'Data\CorCoeff_G2.xls')
display(Table)
%%
BasePlotFileName='Plots\UFS_Fig';
TextSize=14;
SavePlots=1;
Fig.Fig=1;
Fig.TextStyle='%4.3f';
H=[0.25,0.3:0.01:1 1:-0.01:0.3,0.25];
N=length(H);
Fig.ColorMAP=hsv2rgb([H',ones(N,1),ones(N,1)]);
Fig.ColorRenge=[-1,1];
Fig.Position=[50,50,1600,800];
Fig.TextSize=10;
% Fig.Position=[50,50,800,500];
% Fig.TextSize=14;
PlotNiceTabel(Table,Fig);
if SavePlots
FileName=[BasePlotFileName,'2_CorrCoef'];
saveas(gcf,[FileName,'.jpg']);
saveas(gcf,[FileName,'.emf']);
end